<template>
  <a-card 
    :title="project.name" 
    :bordered="true"
    class="project-card"
    :hoverable="true"
  >
    <template #extra>
      <div v-if="isAdmin" class="action-buttons">
        <a-button 
          type="link" 
          size="small" 
          @click="onEdit"
          :icon="h(EditOutlined)"
        >
          编辑
        </a-button>
        <a-popconfirm
          title="确定要删除这个项目吗？"
          ok-text="确定"
          cancel-text="取消"
          @confirm="onDelete"
        >
          <a-button 
            type="link" 
            size="small" 
            danger
            :icon="h(DeleteOutlined)"
          >
            删除
          </a-button>
        </a-popconfirm>
      </div>
    </template>

    <div class="project-description">
      {{ project.description || '暂无描述' }}
    </div>

    <div class="project-group" v-if="group">
      <a-tag color="blue">{{ group.name }}</a-tag>
    </div>

    <div class="environments-section">
      <h4>环境配置</h4>
      <div class="environments-list">
        <div 
          v-for="environment in project.environments" 
          :key="environment.id"
          class="environment-item"
        >
          <div class="environment-info">
            <span class="environment-name">{{ environment.name }}</span>
            <a-tag 
              :color="getEnvironmentTypeColor(environment.type)"
              size="small"
            >
              {{ getEnvironmentTypeName(environment.type) }}
            </a-tag>
          </div>
          
          <div class="environment-hosts" v-if="environment.hosts.length > 0">
            <div 
              v-for="host in environment.hosts" 
              :key="host"
              class="host-item"
            >
              <a-tag size="small">{{ host }}</a-tag>
            </div>
          </div>

          <div class="environment-control">
            <a-switch
              v-model:checked="environment.isActive"
              :loading="switchLoading[environment.id]"
              @change="(checked: boolean) => onEnvironmentToggle(environment, checked)"
              :disabled="!isAdmin"
            />
            <span class="switch-label">
              {{ environment.isActive ? '已激活' : '未激活' }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script setup lang="ts">
import { ref, h } from 'vue';
import { message } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import type { ProjectCardProps, Environment, EnvironmentType, EnvironmentOperationResponse } from '@/types';
import { projectApi } from '@/api';

// Props
const props = defineProps<ProjectCardProps>();

// Emits
const emit = defineEmits<{
  edit: [projectId: string];
  delete: [projectId: string];
  refresh: [];
}>();

// 响应式数据
const switchLoading = ref<Record<string, boolean>>({});

// 环境类型颜色映射
const environmentTypeColors: Record<EnvironmentType, string> = {
  development: 'green',
  test: 'orange',
  preview: 'purple',
  production: 'red',
  custom: 'blue',
};

// 环境类型名称映射
const environmentTypeNames: Record<EnvironmentType, string> = {
  development: '开发环境',
  test: '测试环境',
  preview: '预发布环境',
  production: '正式环境',
  custom: '自定义环境',
};

// 获取环境类型颜色
const getEnvironmentTypeColor = (type: EnvironmentType): string => {
  return environmentTypeColors[type] || 'default';
};

// 获取环境类型名称
const getEnvironmentTypeName = (type: EnvironmentType): string => {
  return environmentTypeNames[type] || '未知环境';
};

// 强制清除浏览器缓存和DNS缓存
const forceClearBrowserCache = async () => {
  if (typeof window === 'undefined') return;
  
  console.log('[NoHost] 开始强制清除浏览器缓存...');
  
  try {
    // 方法1: 清除DNS缓存 (通过访问不存在的域名)
    const clearCacheImg = new Image();
    clearCacheImg.src = `https://clear-cache-${Date.now()}.invalid/clear.gif`;
    
    // 方法2: 强制刷新当前页面 (如果支持)
    if (window.location && window.location.reload) {
      // 使用 replace 避免在历史记录中留下痕迹
      const currentUrl = window.location.href;
      const newUrl = currentUrl + (currentUrl.includes('?') ? '&' : '?') + `_t=${Date.now()}`;
      window.history.replaceState(null, '', newUrl);
    }
    
    // 方法3: 清除可能的 localStorage 缓存
    try {
      const keys = Object.keys(localStorage);
      keys.forEach(key => {
        if (key.includes('cache') || key.includes('Cache')) {
          localStorage.removeItem(key);
        }
      });
    } catch (e) {
      // 忽略错误
    }
    
    // 方法4: 触发多个网络请求，强制刷新连接池
    const testUrls = [
      `https://test-${Date.now()}.example.com/test1`,
      `https://test-${Date.now()}.example.com/test2`,
      `https://test-${Date.now()}.example.com/test3`
    ];
    
    testUrls.forEach(url => {
      try {
        fetch(url, { method: 'HEAD', mode: 'no-cors' }).catch(() => {});
      } catch (e) {
        // 忽略错误
      }
    });
    
    console.log('[NoHost] 浏览器缓存清除完成');
    
  } catch (error) {
    console.warn('[NoHost] 清除浏览器缓存失败:', error);
  }
};

// 环境开关切换处理 (实时同步优化版)
const onEnvironmentToggle = async (environment: Environment, checked: boolean) => {
  switchLoading.value[environment.id] = true;
  
  try {
    let response: EnvironmentOperationResponse;
    if (checked) {
      response = await projectApi.activateEnvironment(props.project.id, environment.id);
      message.success(`${environment.name} 激活成功 - 立即生效`);
    } else {
      response = await projectApi.deactivateEnvironment(props.project.id, environment.id);
      message.success(`${environment.name} 取消激活成功 - 立即生效`);
    }
    
    // 如果后端返回了forceRefresh标识，进行强制刷新
    if (response.data?.forceRefresh) {
      console.log('[NoHost] 检测到强制刷新标识，正在执行实时同步...');
      
      try {
        // 立即调用强制刷新Whistle规则接口
        await projectApi.forceRefreshRules();
        console.log('[NoHost] Whistle规则强制刷新完成');
      } catch (refreshError) {
        console.warn('[NoHost] Whistle规则强制刷新失败:', refreshError);
        // 不影响主流程，只是记录警告
      }
      
      // 强制清除浏览器缓存和DNS缓存
      await forceClearBrowserCache();
    }
    
    // 立即刷新数据
    emit('refresh');
    
    // 显示响应时间信息（如果有）
    if (response.data?.responseTime) {
      console.log(`[NoHost] 环境切换响应时间: ${response.data.responseTime}ms`);
    }
    
  } catch (error: any) {
    message.error(error.message || '操作失败');
    // 恢复开关状态
    environment.isActive = !checked;
  } finally {
    switchLoading.value[environment.id] = false;
  }
};

// 编辑项目
const onEdit = () => {
  emit('edit', props.project.id);
};

// 删除项目
const onDelete = async () => {
  try {
    await projectApi.delete(props.project.id);
    message.success('项目删除成功');
    emit('delete', props.project.id);
  } catch (error: any) {
    message.error(error.message || '删除失败');
  }
};
</script>

<style scoped>
.project-card {
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.project-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.project-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.project-group {
  margin-bottom: 16px;
}

.environments-section h4 {
  margin: 16px 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.environments-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.environment-item {
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 6px;
  background-color: #fafafa;
}

.environment-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.environment-name {
  font-weight: 500;
  color: #333;
}

.environment-hosts {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  margin-bottom: 8px;
}

.host-item {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.environment-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.switch-label {
  font-size: 12px;
  color: #666;
}
</style>
